package com.hue.gulimail.gulimailsearch.service.impl;

import com.alibaba.fastjson.JSON;
import com.hue.common.to.es.SkuEsModel;
import com.hue.gulimail.gulimailsearch.config.ElasticSearchConfig;
import com.hue.gulimail.gulimailsearch.constant.IndexConstant;
import com.hue.gulimail.gulimailsearch.service.ElasticProductService;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.Index;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

@Service
public class ElasticProductServiceImpl implements ElasticProductService {
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public void saveProduct(List<SkuEsModel> skuEsModels) throws IOException {
        //1.建立product索引的映射关系
        //2.保存数据
        BulkRequest bulkRequest = new BulkRequest(IndexConstant.PRODUCE_INDEX);
        for (SkuEsModel skuEsModel : skuEsModels) {
            IndexRequest request = new IndexRequest();
            request.id(skuEsModel.getSkuId().toString());
            String json = JSON.toJSONString(skuEsModel);
            System.out.println(json);
            request.source(json, XContentType.JSON);
            bulkRequest.add(request);
        }
        BulkResponse response = restHighLevelClient.bulk(bulkRequest, ElasticSearchConfig.COMMON_OPTIONS);
        boolean b = response.hasFailures();
        if (b) {
            throw new RuntimeException("商品上架错误:" + response.getItems());
        }
    }
}
